import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Input,
  Button,
  Upload,
  Space,
  Tabs,
  Table,
  Modal,
  message,
  Row,
  Col,
  Typography,
  Tag,


} from 'antd';
import {
  UploadOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  FileOutlined,
  SaveOutlined,
  BuildOutlined,
  ShopOutlined,
  SafetyCertificateOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import type { UploadFile } from 'antd/es/upload/interface';

const { Title, Text } = Typography;
const { TextArea } = Input;

// 数据接口定义
interface CompanyInfo {
  name: string;
  description: string;
  address: string;
  phone: string;
  email: string;
  website: string;
  founded: string;
  employees: string;
  industry: string;
}

interface Product {
  id: string;
  name: string;
  category: string;
  description: string;
  features: string[];
  status: 'active' | 'inactive';
  createdAt: string;
}

interface Qualification {
  id: string;
  name: string;
  type: string;
  issuer: string;
  issueDate: string;
  expiryDate: string;
  fileUrl: string;
  status: 'valid' | 'expired' | 'pending';
}

const EnterpriseManagement: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [companyForm] = Form.useForm();
  const [productForm] = Form.useForm();
  const [isProductModalVisible, setIsProductModalVisible] = useState(false);
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);
  const [companyInfo, setCompanyInfo] = useState<CompanyInfo>({
    name: '',
    description: '',
    address: '',
    phone: '',
    email: '',
    website: '',
    founded: '',
    employees: '',
    industry: '',
  });
  const [products, setProducts] = useState<Product[]>([]);
  const [qualifications, setQualifications] = useState<Qualification[]>([]);
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  // 模拟数据
  const mockCompanyInfo: CompanyInfo = {
    name: 'GEO智能科技有限公司',
    description: '专注于生成式引擎优化和AI智能营销解决方案的高科技企业，致力于帮助企业提升数字化营销效果。',
    address: '北京市海淀区中关村科技园区创新大厦A座15层',
    phone: '+86-10-8888-8888',
    email: 'contact@geo-tech.com',
    website: 'https://www.geo-tech.com',
    founded: '2020-01-01',
    employees: '50-100人',
    industry: '人工智能',
  };

  const mockProducts: Product[] = [
    {
      id: '1',
      name: 'GEO智能优化平台',
      category: 'AI营销',
      description: '基于大模型的生成式引擎优化平台，提供关键词分析、内容生成等功能',
      features: ['关键词智能分析', '内容自动生成', '效果实时监控', '多模型支持'],
      status: 'active',
      createdAt: '2024-01-01',
    },
    {
      id: '2',
      name: '智能内容管理系统',
      category: '内容管理',
      description: '支持多模态内容管理的智能化内容创作与发布系统',
      features: ['多媒体支持', '智能编辑', '自动发布', '版本管理'],
      status: 'active',
      createdAt: '2024-01-15',
    },
  ];

  const mockQualifications: Qualification[] = [
    {
      id: '1',
      name: '高新技术企业认定证书',
      type: '企业资质',
      issuer: '北京市科学技术委员会',
      issueDate: '2023-01-01',
      expiryDate: '2026-01-01',
      fileUrl: '/certificates/high-tech.pdf',
      status: 'valid',
    },
    {
      id: '2',
      name: 'ISO 9001质量管理体系认证',
      type: '质量认证',
      issuer: '中国质量认证中心',
      issueDate: '2023-06-01',
      expiryDate: '2026-06-01',
      fileUrl: '/certificates/iso9001.pdf',
      status: 'valid',
    },
    {
      id: '3',
      name: '软件著作权登记证书',
      type: '知识产权',
      issuer: '国家版权局',
      issueDate: '2023-03-15',
      expiryDate: '2073-03-15',
      fileUrl: '/certificates/software-copyright.pdf',
      status: 'valid',
    },
  ];

  useEffect(() => {
    loadCompanyData();
  }, []);

  const loadCompanyData = async () => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 1000));
      setCompanyInfo(mockCompanyInfo);
      setProducts(mockProducts);
      setQualifications(mockQualifications);
      companyForm.setFieldsValue(mockCompanyInfo);
    } catch (error) {
      message.error('加载企业信息失败');
    } finally {
      setLoading(false);
    }
  };

  // 产品管理表格列
  const productColumns: ColumnsType<Product> = [
    {
      title: '产品名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string) => <Text strong>{text}</Text>,
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      render: (category: string) => <Tag color="blue">{category}</Tag>,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={status === 'active' ? 'green' : 'default'}>
          {status === 'active' ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date: string) => new Date(date).toLocaleDateString('zh-CN'),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button
            type="primary"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEditProduct(record)}
          >
            编辑
          </Button>
          <Button
            danger
            size="small"
            icon={<DeleteOutlined />}
            onClick={() => handleDeleteProduct(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 资质管理表格列
  const qualificationColumns: ColumnsType<Qualification> = [
    {
      title: '证书名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string) => <Text strong>{text}</Text>,
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => <Tag color="orange">{type}</Tag>,
    },
    {
      title: '颁发机构',
      dataIndex: 'issuer',
      key: 'issuer',
    },
    {
      title: '有效期',
      key: 'validity',
      render: (_, record) => (
        <span>
          {record.issueDate} 至 {record.expiryDate}
        </span>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const config = {
          valid: { color: 'green', text: '有效' },
          expired: { color: 'red', text: '已过期' },
          pending: { color: 'orange', text: '待审核' },
        };
        const { color, text } = config[status as keyof typeof config];
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button size="small" icon={<FileOutlined />}>
            查看
          </Button>
          <Button
            danger
            size="small"
            icon={<DeleteOutlined />}
            onClick={() => handleDeleteQualification(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const handleSaveCompanyInfo = async (values: CompanyInfo) => {
    try {
      setCompanyInfo(values);
      message.success('企业信息保存成功');
    } catch (error) {
      message.error('保存失败');
    }
  };

  const handleEditProduct = (product: Product) => {
    setEditingProduct(product);
    productForm.setFieldsValue({
      ...product,
      features: product.features.join('\n'),
    });
    setIsProductModalVisible(true);
  };

  const handleDeleteProduct = async (id: string) => {
    try {
      setProducts(prev => prev.filter(p => p.id !== id));
      message.success('删除成功');
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleSaveProduct = async (values: any) => {
    try {
      const features = values.features.split('\n').filter((f: string) => f.trim());
      
      if (editingProduct) {
        setProducts(prev => prev.map(p => 
          p.id === editingProduct.id ? { ...p, ...values, features } : p
        ));
        message.success('更新成功');
      } else {
        const newProduct: Product = {
          id: Date.now().toString(),
          ...values,
          features,
          status: 'active' as const,
          createdAt: new Date().toISOString().split('T')[0],
        };
        setProducts(prev => [newProduct, ...prev]);
        message.success('添加成功');
      }
      setIsProductModalVisible(false);
      setEditingProduct(null);
      productForm.resetFields();
    } catch (error) {
      message.error('保存失败');
    }
  };

  const handleDeleteQualification = async (id: string) => {
    try {
      setQualifications(prev => prev.filter(q => q.id !== id));
      message.success('删除成功');
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleUpload = (info: any) => {
    setFileList(info.fileList);
    if (info.file.status === 'done') {
      message.success(`${info.file.name} 文件上传成功`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 文件上传失败`);
    }
  };

  const tabItems = [
    {
      key: 'company',
      label: (
        <span>
          <ShopOutlined />
          企业资料
        </span>
      ),
      children: (
        <Card>
          <Form
            form={companyForm}
            layout="vertical"
            onFinish={handleSaveCompanyInfo}
            initialValues={companyInfo}
          >
            <Row gutter={24}>
              <Col xs={24} md={12}>
                <Form.Item
                  name="name"
                  label="企业名称"
                  rules={[{ required: true, message: '请输入企业名称' }]}
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col xs={24} md={12}>
                <Form.Item
                  name="industry"
                  label="所属行业"
                  rules={[{ required: true, message: '请输入所属行业' }]}
                >
                  <Input />
                </Form.Item>
              </Col>
            </Row>

            <Form.Item
              name="description"
              label="企业简介"
              rules={[{ required: true, message: '请输入企业简介' }]}
            >
              <TextArea rows={4} />
            </Form.Item>

            <Row gutter={24}>
              <Col xs={24} md={12}>
                <Form.Item
                  name="founded"
                  label="成立时间"
                  rules={[{ required: true, message: '请输入成立时间' }]}
                >
                  <Input type="date" />
                </Form.Item>
              </Col>
              <Col xs={24} md={12}>
                <Form.Item
                  name="employees"
                  label="员工规模"
                  rules={[{ required: true, message: '请输入员工规模' }]}
                >
                  <Input />
                </Form.Item>
              </Col>
            </Row>

            <Form.Item
              name="address"
              label="企业地址"
              rules={[{ required: true, message: '请输入企业地址' }]}
            >
              <Input />
            </Form.Item>

            <Row gutter={24}>
              <Col xs={24} md={8}>
                <Form.Item
                  name="phone"
                  label="联系电话"
                  rules={[{ required: true, message: '请输入联系电话' }]}
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col xs={24} md={8}>
                <Form.Item
                  name="email"
                  label="联系邮箱"
                  rules={[{ required: true, type: 'email', message: '请输入有效的邮箱地址' }]}
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col xs={24} md={8}>
                <Form.Item
                  name="website"
                  label="官方网站"
                >
                  <Input />
                </Form.Item>
              </Col>
            </Row>

            <Form.Item>
              <Button type="primary" htmlType="submit" icon={<SaveOutlined />}>
                保存企业信息
              </Button>
            </Form.Item>
          </Form>
        </Card>
      ),
    },
    {
      key: 'products',
      label: (
        <span>
          <BuildOutlined />
          产品服务
        </span>
      ),
      children: (
        <div>
          <div style={{ marginBottom: 16 }}>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => {
                setEditingProduct(null);
                productForm.resetFields();
                setIsProductModalVisible(true);
              }}
            >
              添加产品
            </Button>
          </div>
          <Card>
            <Table
              columns={productColumns}
              dataSource={products}
              rowKey="id"
              loading={loading}
            />
          </Card>
        </div>
      ),
    },
    {
      key: 'qualifications',
      label: (
        <span>
          <SafetyCertificateOutlined />
          资质证书
        </span>
      ),
      children: (
        <div>
          <div style={{ marginBottom: 16 }}>
            <Upload
              fileList={fileList}
              onChange={handleUpload}
              beforeUpload={() => false}
              multiple
            >
              <Button icon={<UploadOutlined />}>上传资质证书</Button>
            </Upload>
          </div>
          <Card>
            <Table
              columns={qualificationColumns}
              dataSource={qualifications}
              rowKey="id"
              loading={loading}
            />
          </Card>
        </div>
      ),
    },
  ];

  return (
    <div>
      <Title level={2}>企业信息管理</Title>
      
      <Tabs
        items={tabItems}
        size="large"
      />

      {/* 产品编辑模态框 */}
      <Modal
        title={editingProduct ? '编辑产品' : '添加产品'}
        open={isProductModalVisible}
        onCancel={() => {
          setIsProductModalVisible(false);
          setEditingProduct(null);
          productForm.resetFields();
        }}
        footer={null}
        width={800}
      >
        <Form
          form={productForm}
          layout="vertical"
          onFinish={handleSaveProduct}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="产品名称"
                rules={[{ required: true, message: '请输入产品名称' }]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="category"
                label="产品分类"
                rules={[{ required: true, message: '请输入产品分类' }]}
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>
          
          <Form.Item
            name="description"
            label="产品描述"
            rules={[{ required: true, message: '请输入产品描述' }]}
          >
            <TextArea rows={4} />
          </Form.Item>
          
          <Form.Item
            name="features"
            label="主要功能"
            rules={[{ required: true, message: '请输入主要功能' }]}
            extra="每行一个功能特性"
          >
            <TextArea rows={6} placeholder="功能特性1&#10;功能特性2&#10;功能特性3" />
          </Form.Item>
          
          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button onClick={() => setIsProductModalVisible(false)}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                {editingProduct ? '更新' : '添加'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default EnterpriseManagement;